package IpUtil

import (
	"fmt"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"time"
)

var (
	dbPath string = "./ip2region.xdb"
	ipBuff []byte
)

func init() {
	var err error
	ipBuff, err = xdb.LoadContentFromFile(dbPath)
	if err != nil {
		fmt.Printf("加载数据库数据失败 `%s`: %s\n", dbPath, err)
		return
	}
}

// SearchIP searches for the region information associated with the given IP address.
func SearchIP(ip string) (string, error) {
	searcher, err := xdb.NewWithBuffer(ipBuff)
	if err != nil {
		return "", fmt.Errorf("创建searcher失败: %s", err.Error())
	}
	defer searcher.Close()

	startTime := time.Now()
	region, err := searcher.SearchByStr(ip)
	if err != nil {
		return "", fmt.Errorf("查询ip失败(%s): %s", ip, err)
	}
	fmt.Printf("addr: %s, took: %s\n", region, time.Since(startTime))
	return region, nil
}
